package scatter.notify.rest.notify;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import scatter.common.rest.notify.AbstractNotifyListener;
import scatter.common.rest.notify.NotifyParam;
import scatter.common.rest.tools.InterfaceTool;

import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 邮件通知默认实现
 * </p>
 *
 * @author yangwei
 * @since 2021-08-26 09:56
 */
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE)
public class DefaultEmailNotifyListenerImpl extends AbstractNotifyListener implements InterfaceTool {

	@Autowired
	private IEmailNotifySenderResolver iEmailNotifySenderResolver;
	/**
	 * 缓存 账号对象
	 */
	private ConcurrentHashMap<EmailAccountProperties,MailAccount> cache = new ConcurrentHashMap<>();


	@Override
	protected String supportType() {
		return NotifyParam.Type.email.name();
	}

	@Override
	public void doNotify(NotifyParam notifyParam) {
		EmailAccountProperties emailAccountProperties = iEmailNotifySenderResolver.resolve(notifyParam);
		if (emailAccountProperties == null) {
			log.warn("邮件通知未获取到配置，已忽略发送，发送参数={}",toJsonStr(notifyParam));
		}

		MailUtil.send(
				getMailAccount(emailAccountProperties)
				,notifyParam.getToUser()
						,notifyParam.getTitle()
						,formatParam(notifyParam).stream().collect(Collectors.joining("<br/>"))
						,true
				);
	}

	/**
	 * 获取配置对象
	 * @param emailAccountProperties
	 * @return
	 */
	private MailAccount getMailAccount(EmailAccountProperties emailAccountProperties){
		return cache.computeIfAbsent(emailAccountProperties, key ->
			new MailAccount()
			.setHost(emailAccountProperties.getHost())
			.setPort(emailAccountProperties.getPort())
			.setFrom(emailAccountProperties.getFrom())
			.setUser(emailAccountProperties.getUser())
			.setPass(emailAccountProperties.getPass())
			.setStarttlsEnable(emailAccountProperties.getStarttlsEnable())
			.setSslEnable(emailAccountProperties.getSslEnable())
			.setSocketFactoryClass(emailAccountProperties.getSocketFactoryClass())
			.setSocketFactoryFallback(emailAccountProperties.getSocketFactoryFallback())
			.setSocketFactoryPort(emailAccountProperties.getSocketFactoryPort())
			.setTimeout(emailAccountProperties.getTimeout())
			.setConnectionTimeout(emailAccountProperties.getConnectionTimeout())

		);

	}
}
